<template>
  <div class="merchant-management-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">商户管理</h2>
      <p class="page-subtitle">管理系统中的所有商户信息</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Shop /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">总商户数</div>
            <div class="stat-value">{{ merchants.length }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon active">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">营业中</div>
            <div class="stat-value">{{ activeCount }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon inactive">
            <el-icon><CircleClose /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">已停业</div>
            <div class="stat-value">{{ inactiveCount }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="filter-card" shadow="never">
      <div class="filter-content">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商户名称、地址或电话"
            prefix-icon="Search"
            clearable
            class="search-input"
          />
        </div>
        <div class="filter-right">
          <el-button type="primary" @click="addMerchant">
            <el-icon><Plus /></el-icon>
            添加商户
          </el-button>
          <el-button @click="refreshMerchants" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 商户卡片网格 -->
    <div class="merchants-grid" v-loading="loading">
      <el-card
        v-for="merchant in filteredMerchants"
        :key="merchant.restaurant_id"
        class="merchant-card"
        shadow="hover"
      >
        <div class="merchant-card-header">
          <div class="merchant-image">
            <img
              :src="merchant.image_url || defaultImage"
              :alt="merchant.restaurant_name"
              @error="handleImageError"
            />
          </div>
          <div class="merchant-basic-info">
            <h3 class="merchant-name">{{ merchant.restaurant_name }}</h3>
            <div class="merchant-status">
              <el-switch
                v-model="merchant.status"
                @change="toggleStatus(merchant.restaurant_id, merchant.status)"
                active-color="#67c23a"
                inactive-color="#f56c6c"
                active-text="营业中"
                inactive-text="已停业"
              />
            </div>
          </div>
        </div>

        <div class="merchant-card-content">
          <div class="merchant-info-item">
            <el-icon class="info-icon"><Location /></el-icon>
            <span class="info-text">{{ merchant.address }}</span>
          </div>
          <div class="merchant-info-item">
            <el-icon class="info-icon"><Phone /></el-icon>
            <span class="info-text">{{ merchant.contact_number }}</span>
          </div>
          <div class="merchant-info-item" v-if="merchant.description">
            <el-icon class="info-icon"><Document /></el-icon>
            <span class="info-text">{{ merchant.description }}</span>
          </div>
        </div>

        <div class="merchant-card-actions">
          <el-button
            type="primary"
            size="small"
            @click="showDetails(merchant.restaurant_id)"
          >
            <el-icon><List /></el-icon>
            菜单详情
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="showDetailspu(merchant.restaurant_id)"
          >
            <el-icon><View /></el-icon>
            店铺详情
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteMerchant(merchant.restaurant_id)"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredMerchants.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无商户数据">
        <el-button type="primary" @click="addMerchant">
          添加商户
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  restaurantApi,
  deleteRestaurantApi,
  toggleMerchantStatusApi,
} from "@/utils/api";
import { useRouter } from "vue-router";
import {
  Shop,
  CircleCheck,
  CircleClose,
  Plus,
  Refresh,
  Search,
  Location,
  Phone,
  Document,
  List,
  View,
  Delete
} from '@element-plus/icons-vue';

const router = useRouter();

// 响应式数据
const merchants = ref([]);
const loading = ref(false);
const searchKeyword = ref("");

// 默认图片
const defaultImage = 'http://localhost:3000/images/rest/default.jpg';

// 计算属性
const activeCount = computed(() =>
  merchants.value.filter(merchant => merchant.status).length
);

const inactiveCount = computed(() =>
  merchants.value.filter(merchant => !merchant.status).length
);

const filteredMerchants = computed(() => {
  if (!searchKeyword.value) return merchants.value;

  const keyword = searchKeyword.value.toLowerCase();
  return merchants.value.filter(merchant =>
    merchant.restaurant_name?.toLowerCase().includes(keyword) ||
    merchant.address?.toLowerCase().includes(keyword) ||
    merchant.contact_number?.toLowerCase().includes(keyword)
  );
});

// 获取商户列表
const fetchMerchants = async () => {
  try {
    loading.value = true;
    const res = await restaurantApi();
    merchants.value = res.data.map((item) => ({
      ...item,
      image_url: item.image_url ? `http://localhost:3000/images/rest/${item.image_url}` : null,
      status: item.status === 1,
    }));
    // 根据 restaurant_id 排序
    merchants.value.sort((a, b) => b.restaurant_id - a.restaurant_id);
  } catch (error) {
    console.error("获取商户列表失败:", error);
    ElMessage.error('获取商户列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新商户列表
const refreshMerchants = () => {
  fetchMerchants();
};

// 添加商户
const addMerchant = () => {
  router.push("/home/addrest");
};

// 查看菜单详情
const showDetails = (id) => {
  router.push(`/home/menuList/${id}`);
};

// 查看店铺详情
const showDetailspu = (id) => {
  router.push(`/home/dianpuxiangqing/${id}`);
};

// 删除商户
const deleteMerchant = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该商户吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    );

    const response = await deleteRestaurantApi({ id });
    if (response.code === 200) {
      ElMessage.success('商户删除成功');
      await fetchMerchants();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除商户失败:", error);
      ElMessage.error('删除商户失败');
    }
  }
};

// 切换商户状态
const toggleStatus = async (id, status) => {
  try {
    const newStatus = status ? 1 : 0;
    const response = await toggleMerchantStatusApi({ id, newStatus });

    if (response.code === 200) {
      ElMessage.success(`商户${status ? '启用' : '停用'}成功`);
    } else {
      ElMessage.error(response.message || '状态更新失败');
      // 恢复原状态
      const merchant = merchants.value.find(m => m.restaurant_id === id);
      if (merchant) {
        merchant.status = !status;
      }
    }
  } catch (error) {
    console.error("更新商户状态失败:", error);
    ElMessage.error('状态更新失败');
    // 恢复原状态
    const merchant = merchants.value.find(m => m.restaurant_id === id);
    if (merchant) {
      merchant.status = !status;
    }
  }
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = defaultImage;
};

// 组件挂载时获取数据
onMounted(() => {
  fetchMerchants();
});
</script>

<style lang="less" scoped>
.merchant-management-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }

  .page-subtitle {
    color: #909399;
    margin: 0;
    font-size: 14px;
  }
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;

  :deep(.el-card__body) {
    padding: 20px;
  }

  .stat-content {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: white;

    &.total {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    &.active {
      background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    }

    &.inactive {
      background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    }
  }

  .stat-info {
    flex: 1;

    .stat-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 4px;
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
  border: none;

  :deep(.el-card__body) {
    padding: 16px 20px;
  }
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .filter-left {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }
  }

  .filter-right {
    display: flex;
    gap: 12px;
  }
}

.merchants-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.merchant-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.merchant-card-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;

  .merchant-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .merchant-basic-info {
    flex: 1;

    .merchant-name {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 12px 0;
    }

    .merchant-status {
      :deep(.el-switch__label) {
        font-size: 12px;
      }
    }
  }
}

.merchant-card-content {
  margin-bottom: 16px;

  .merchant-info-item {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .info-icon {
      color: #909399;
      font-size: 14px;
      margin-top: 2px;
      flex-shrink: 0;
    }

    .info-text {
      font-size: 14px;
      color: #606266;
      line-height: 1.4;
    }
  }
}

.merchant-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f0f2f5;
  flex-wrap: wrap;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
}

// 响应式设计
@media (max-width: 768px) {
  .merchant-management-page {
    padding: 16px;
  }

  .stats-cards {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .filter-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .search-input {
      width: 100%;
    }
  }

  .merchants-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .merchant-card-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
